package com.uziot.bucket.security.config.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uziot.bucket.security.util.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * @author shidt
 * @version V1.0
 * @className AuthenticationEntryPointImpl
 * @date 2020-11-16 23:48:56
 * @description 认证失败处理类 返回未授权
 */

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;
    private static final Logger log = LoggerFactory.getLogger(AuthenticationEntryPointImpl.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        String requestUri = request.getRequestURI();
        log.debug("请求访问[{}]接口，认证失败，访问已被拒绝", requestUri);

        String msg = "请求访问：" + requestUri + "，认证失败，无法访问系统资源";
        JSONObject result = new JSONObject();
        result.put("code", 403);
        result.put("msg", msg);
        String jsonString = JSON.toJSONString(result);
        ServletUtils.writeResponse(response, jsonString);
    }
}
